﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CommerceOne.Common;
using CommerceOne.Domains.Commons;
using CommerceOne.Domains.IRepositories;
using CommerceOne.Domains.SqlRepositories;

namespace CommerceOne.Widgets.ProductGrid
{
    public class ProductGridController
    {
        private const int MaxLength = 30;
        private readonly IProductRepository _productRepository = new SqlProductRepository();

        /// <summary>
        /// Gets the view model.
        /// </summary>
        /// <param name="categoryId">The category id.</param>
        /// <param name="sortingType">Type of the sorting.</param>
        /// <param name="page">The page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns></returns>
        public ProductGridViewModel GetViewModel(int categoryId, ProductSortType sortingType, int page, int pageSize)
        {
            var viewModel = new ProductGridViewModel();
            int numberOfRecord;
            viewModel.ProductGrid = this._productRepository.GetProducts(categoryId, sortingType, page, pageSize, out numberOfRecord);
            viewModel.TotalRecord = numberOfRecord;

            foreach (var item in viewModel.ProductGrid)
            {
                item.Url = UrlBuilderService.Instance.GetUrlRoute(PageType.ProductDetail, item.ID, 1, item.Name, string.Empty);
                item.ShortName = item.Name;
                if (item.ShortName.Length > MaxLength) item.ShortName = item.Name.Substring(0, MaxLength) + "...";
                foreach (var photoItem in item.ProductPhoto)
                {
                    if (!string.IsNullOrEmpty(photoItem.Home)) photoItem.Home = DisplayUtil.GetImageUrl(photoItem.Home);
                    if (!string.IsNullOrEmpty(photoItem.Large)) photoItem.Large = DisplayUtil.GetImageUrl(photoItem.Large);
                    if (!string.IsNullOrEmpty(photoItem.Medium)) photoItem.Medium = DisplayUtil.GetImageUrl(photoItem.Medium);
                    if (!string.IsNullOrEmpty(photoItem.ThickBox)) photoItem.ThickBox = DisplayUtil.GetImageUrl(photoItem.ThickBox);
                }
            }

            return viewModel;
        }
    }
}